import { defineStore } from "pinia";
import { computed, reactive, ref } from "vue";
import { Local } from '@/utils/storage'
import { STORE_TAB_VIEW_CONFIG } from '@/stores/constant/cacheKey'
import { useConfigStore } from '@/stores/config'

/** 菜单、权限信息 */
export const useMenuStore = defineStore('menu', () => {
    /** 全部菜单 */
    let menus = reactive<menuModel[]>([]);
    /** 导航栏 - 菜单 */
    let tabsMenu = reactive<tabsMenuModel[]>([]);

    /** 首页是否初始化完成 */
    let indexInitSuccess = ref(false);
    /** 远程路由是否加载完成 */
    let remoteRouteLoaded = ref(false);
    /** 权限是否加载完成 */
    let permissionLoaded = ref(false);

    /** 侧边栏 - 菜单默认激活项 */
    let menuDefaultActive = ref('');
    /** 导航栏 - 菜单激活项 */
    let tabsMenuActive = ref('');

    const configStore = useConfigStore();

    /** 侧边栏 - 菜单数据 */
    const asideMenus = computed(() => {
        const handle = (list: menuModel[]) => {
            let result: menuModel[] = [];
            if (!list || list.length === 0) {
                return [];
            }

            result.push(...list.filter(item => item.menuType === 'menu'));
            if (result && result.length > 0) {
                for (let i = 0; i < result.length; i++) {
                    let childrenList = result[i].children;
                    if (!childrenList || childrenList.length === 0) {
                        continue;
                    }
                    childrenList = handle(childrenList);
                }
            }

            return result;
        }

        const result = handle(menus ?? []);
        return result;
    })

    /** 路由信息 */
    const routerInfo = computed(() => {
        let result: menuModel[] = [];
        const handle = (list: menuModel[]) => {
            if (!list || list.length === 0) {
                return [];
            }

            let menuItem = list.filter(item => item.routerPath && item.componentPath);
            result.push(...menuItem);

            for (let i = 0; i < list.length; i++) {
                let childrenList = list[i].children;
                if (!childrenList || childrenList.length === 0) {
                    continue;
                }
                handle(childrenList);
            }
        }
        handle(menus ?? []);
        return result;
    })

    /** 权限信息 */
    const permissionInfo = computed(() => {
        let result: menuModel[] = [];
        const handle = (list: menuModel[]) => {
            if (!list || list.length === 0) {
                return [];
            }

            let menuItem = list.filter(item => item.permission);
            result.push(...menuItem);

            for (let i = 0; i < list.length; i++) {
                let childrenList = list[i].children;
                if (!childrenList || childrenList.length === 0) {
                    continue;
                }
                handle(childrenList);
            }
        }
        handle(menus ?? []);
        permissionLoaded.value = true;
        return result;
    })

    /** 初始化标签信息 */
    const initTab = () => {
        let storage = Local.get(STORE_TAB_VIEW_CONFIG);
        if (storage) {
            tabsMenu.push(...storage);
        }

        let config = configStore.config;
        if (config && config.menuActive) {
            tabsMenuActive.value = config.menuActive;
            menuDefaultActive.value = config.menuActive;
        }
    }

    /**
     * 添加标签
     * @param {string} routerPath 路由信息
     */
    const addTab = (routerPath: string): void => {
        tabsMenuActive.value = routerPath;
        menuDefaultActive.value = routerPath;

        configStore.setMenuActive(routerPath);

        let isExist = tabsMenu.findIndex(item => item.routerPath === routerPath) !== -1;
        if (isExist) {
            return;
        }

        let menuInfo = routerInfo.value.filter(item => item.routerPath === routerPath)[0];

        tabsMenu.push({
            routerPath: routerPath,
            title: menuInfo.title ?? ''
        });

        Local.set(STORE_TAB_VIEW_CONFIG, tabsMenu);
    }

    /**
     * 关闭标签
     * @param {string} routerPath 路由信息
     * @returns {string} 前一个标签路由
     */
    const closeTab = (routerPath: string): string => {
        let index = tabsMenu.findIndex(item => item.routerPath === routerPath);
        if (index > -1) {
            tabsMenu.splice(index, 1);
        }

        let result: string = '';

        // 选中前一个菜单
        if (tabsMenu && tabsMenu.length > 0) {
            let prevTab = tabsMenu.reverse()[0];
            result = prevTab.routerPath ?? '';
        }

        menuDefaultActive.value = result;
        tabsMenuActive.value = result;

        Local.set(STORE_TAB_VIEW_CONFIG, tabsMenu);
        configStore.setMenuActive(result);

        return result;
    }

    return {
        menus,

        asideMenus,
        routerInfo,
        permissionInfo,

        indexInitSuccess,
        remoteRouteLoaded,

        menuDefaultActive,
        tabsMenu,
        initTab,
        addTab,
        closeTab,
        tabsMenuActive,

        permissionLoaded
    }
});

/**
 * 菜单模型接口
 */
interface menuModel {
    /** Id */
    id?: number
    /** 标题 */
    title?: string
    /** 图标 */
    icon?: string
    /** 类型 */
    menuType?: string
    /** 组件路径 */
    componentPath?: string
    /** 路由路径 */
    routerPath?: string
    /** 权限名称 */
    permission?: string
    /** 子级菜单 */
    children?: menuModel[]
}

/**
 * 导航栏 - 菜单模型
 */
interface tabsMenuModel {
    /** 路由信息 */
    routerPath: string
    /** 标题 */
    title: string
}